<template>
  <i-biz-control-base :controller="c">
    <i-biz-row :class="ns.b('content')" :layout="{ layout: 'FLEX' }">
      <template v-if="!!c.state.isCreated">
        <i-biz-col
          v-for="panelItem in c.model.rootPanelItems"
          :key="panelItem.id"
          :layoutPos="calcColLayoutPos(panelItem)"
          :state="c.panelItems[panelItem.id].state"
        >
          <i-biz-panel-detail-shell
            :container="c"
            :controls="controls"
            :modelData="panelItem"
            :layoutPos="{ layout: 'FLEX' }"
          />
        </i-biz-col>
      </template>
    </i-biz-row>
  </i-biz-control-base>
</template>
<script lang="ts">
export default {
  options: {
    addGlobalClass: true,
    virtualHost: true,
    styleIsolation: "shared"
  },
};
</script>
<script setup lang="ts">
import {
  IViewLayoutPanel,
  IControl,
  IPanelItem,
  ILayoutPos,
} from "@ibiz/model-core";
import {
  IController,
  IControlProvider,
  ViewLayoutPanelController,
} from "@ibiz-template/runtime";
import { useControlController, useNamespace } from "@/use";
import { PropType, reactive, watch } from "vue";

// 定义组件接收的属性
const props = defineProps({
  modelData: {
    type: Object as PropType<IViewLayoutPanel>,
    required: true,
  },
  context: {
    type: Object as PropType<IContext>,
    required: true,
  },
  params: {
    type: Object as PropType<IParams>,
    default: () => ({}),
  },
  provider: {
    type: Object as PropType<IControlProvider>,
  },
  container: {
    type: Object as PropType<IController>,
  },
  controls: {
    type: Array as PropType<
      {
        modelData: IControl;
        slotProps: IData;
      }[]
    >,
    default: () => [],
  },
  data: Object as PropType<IData>,
});

const c = useControlController(
  (...args) => new ViewLayoutPanelController(...args, props.container)
);

const ns = useNamespace(`control-${c.model.controlType!.toLowerCase()}`);

// 监听data的变化
watch(
  () => props.data,
  (newVal) => {
    if (newVal) {
      c.setInputData(newVal);
      c.load();
    }
  },
  {
    immediate: true,
  }
);

// 在onCreated事件中将panelItems的state转换为响应式
c.evt.on("onCreated", () => {
  const keys = Object.keys(c.panelItems);
  keys.forEach((key) => {
    const panelItem = c.panelItems[key];
    panelItem.state = reactive(panelItem.state);
  });
});

const calcColLayoutPos = (panelItem: IPanelItem): ILayoutPos => {
  return {
    ...panelItem.layoutPos,
    layout: "FLEX",
  } as ILayoutPos;
};
</script>
<style lang="scss">
@import "./i-biz-view-layout-panel.scss";
</style>
